package com.mars.springbootdemo.file.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("file")
public class FileController {

    @PostMapping("upload")
    public String upload(String filename, MultipartFile file) throws IOException {
        file.transferTo(Paths.get("C:\\mydata\\workspace\\IDEA\\springboot-demo\\doc", filename));
        return "success";
    }

    @GetMapping("download")
    public ResponseEntity<StreamingResponseBody> downloadFile() {
        return testFile();
    }


    public ResponseEntity<StreamingResponseBody> testFile() {
        ContentDisposition contentDisposition = ContentDisposition.attachment()
                .filename("text.txt")
                .build();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString())
                .body(outputStream -> {
                    IoUtil.copy(ResourceUtil.getStream("test.txt"), outputStream);
                });
    }

}
